require File.expand_path('../../config/environment',  __FILE__)

agent = Mechanize.new
agent.max_history = 1
agent.cookie_jar.load_cookiestxt(File.new("#{Rails.root}/data/cookies_2669265134.txt"))

#FIXME 0
last_id = 0

def process_hotsale(page,shop, agent)
  items = page.search("div.week-hotsale li.list-item")
  if items.size > 0
    items.each do |li|
      Thread.new(li, shop) do |list_item, s|
        css_title = list_item.css('p.title')
        next if css_title.blank?
        merchandise = s.merchandises.build
        merchandise.name = css_title.text
        merchandise.item_id = css_title.css('a').first['href'].scan(/\d+$/).to_s
        merchandise.img_url = list_item.css('div.pic a img').first['src']
        merchandise.price = list_item.css('p.price span').text.scan(/\d+\.\d+/).to_s
        merchandise.commission = list_item.css('p.sale span.commission').text.scan(/(\d+\.\d+)%/).to_s
        merchandise.commission_num = merchandise.price * merchandise.commission / 100
        merchandise.total_num = list_item.css('p.sale span.orange').text
        merchandise.prom_url = process_prom_url(merchandise.item_id, agent)
        Rails.logger.info "商品保存失败#{page.uri}" unless merchandise.save
      end
    end
  else
    Rails.logger.info "商品数据为0 #{shop.id} -- #{page.uri}"
  end
end

def process_prom_url(item_id, agent)
   aurl = "http://www.alimama.com/union/promotion/allCode.htm?auction_id=#{item_id}"
   page2 = agent.get(aurl)
   link_code = page2.search("#J_codeArea").text
   link_code.sub("mm_29950208_0_0","mm_13357908_0_0")
end

while true
  begin
  shop_tasks = Shop.all(:conditions => "id > #{last_id} AND user_id IS NOT NULL", :order => 'id ASC', :limit => 100)
  break if shop_tasks.blank?
  last_id = shop_tasks.last.id

  shop_tasks.each do |shop_task|
    page = agent.get shop_task.shop_detail_url
    unless (page.title =~ /阿里妈妈登录页面/).nil? #未登录或登陆过期
      Rails.logger.error "会话过期"
      exit
    end
    credit_rate = page.search("span.steelBlue").text
    if credit_rate.present?
      shop_task.credit_rate = credit_rate
      shop_task.save
      process_hotsale(page, shop_task, agent)
    else
      Rails.logger.warn "解析推广出错,此用户没有推广或其它错误 #{page.uri}"
    end
  end
  rescue
    Rails.logger.info "出错未知异常#{$!}"
  end
end
